import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluent_ui/fluent_ui.dart' hide IconButton;
import 'package:flutter/cupertino.dart' show CupertinoIcons;
import 'package:flutter/material.dart'
    show Material, InkWell, Icons, IconButton;
import 'package:fnos_tv_desktop/core/api/bean/media_info_result.dart';
import 'package:provider/provider.dart';

import '../../../application/nav.dart';
import '../../../core/api/api.dart';
import '../../../core/model/user_info.dart';
import '../main_page_model.dart';

class MediaItem extends StatefulWidget {
  final MediaInfoResult info;

  const MediaItem({super.key, required this.info});

  @override
  State<MediaItem> createState() => _MediaItemState();
}

class _MediaItemState extends State<MediaItem> {
  late final subtitle = getSubtitle();
  bool isHover = false;
  final api = Api();

  @override
  Widget build(BuildContext context) {
    final userInfo = context.watch<UserInfo>();
    return MouseRegion(
      onEnter: (event) {
        setState(() {
          isHover = true;
        });
      },
      onExit: (event) {
        setState(() {
          isHover = false;
        });
      },
      child: Container(
        margin: const EdgeInsets.all(8),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            hoverColor: Colors.transparent,
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
            borderRadius: BorderRadius.circular(12),
            onTap: () {
              context.read<MainPageModel>().goToDetails(widget.info);
            },
            child: SizedBox(
              width: 155,
              height: 285,
              child: Stack(
                children: [
                  Column(
                    children: [
                      Expanded(
                        child: Card(
                          padding: EdgeInsets.zero,
                          borderColor: FluentTheme.of(context).shadowColor,
                          borderRadius: BorderRadius.circular(12),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(12),
                            child: Stack(
                              fit: StackFit.expand,
                              children: [
                                if (widget.info.poster != null)
                                  CachedNetworkImage(
                                    imageUrl: api.imageUrl(widget.info.poster!),
                                    fit: BoxFit.cover,
                                    errorWidget: (context, url, error) => Center(
                                      child: const Icon(FluentIcons.error),
                                    ),
                                  ),
                                if (widget.info.type == 'Directory')
                                  Card(
                                    child: Center(
                                      child: Icon(Icons.folder, size: 60),
                                    ),
                                  ),
                                Stack(
                                  children: [
                                    AnimatedContainer(
                                      duration: const Duration(milliseconds: 200),
                                      decoration: BoxDecoration(
                                        color: isHover
                                            ? Colors.black.withValues(alpha: 0.6)
                                            : null,
                                      ),
                                    ),
                                    if (widget.info.type != 'Directory' &&
                                        isHover)
                                      Center(
                                        child: IconButton(
                                          iconSize: 50,
                                          onPressed: () {
                                            Nav.goToPlay(widget.info);
                                          },
                                          icon: Icon(
                                            CupertinoIcons.play_circle,
                                            color: Colors.white,
                                          ),
                                        ),
                                      ),
                                    if (isHover)
                                      Align(
                                        alignment: Alignment.bottomCenter,
                                        child: Row(
                                          mainAxisSize: MainAxisSize.max,
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: [
                                            IconButton(
                                              icon: Icon(Icons.check),
                                              color: widget.info.watched != 1
                                                  ? Colors.white
                                                  : FluentTheme.of(
                                                      context,
                                                    ).accentColor,
                                              onPressed: () {},
                                            ),
                                            IconButton(
                                              icon: Icon(
                                                Icons.favorite,
                                                color: widget.info.isFavorite == 1
                                                    ? Colors.red
                                                    : null,
                                              ),
                                              onPressed: () {},
                                            ),
                                            if (widget.info.type != 'Directory' &&
                                                userInfo.isAdmin)
                                              IconButton(
                                                icon: Icon(Icons.more_horiz),
                                                onPressed: () {},
                                              ),
                                          ],
                                        ),
                                      ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.all(8),
                        child: Column(
                          children: [
                            Tooltip(
                              message: widget.info.title,
                              child: Text(
                                widget.info.title,
                                style: isHover
                                    ? FluentTheme.of(
                                        context,
                                      ).typography.body!.copyWith(
                                        color: FluentTheme.of(
                                          context,
                                        ).accentColor,
                                      )
                                    : FluentTheme.of(context).typography.body,
                                maxLines: 1,
                                overflow: TextOverflow.fade,
                                softWrap: false,
                              ),
                            ),
                            Text(
                              subtitle,
                              style: FluentTheme.of(context).typography.caption!
                                  .copyWith(
                                    color: FluentTheme.of(
                                      context,
                                    ).inactiveColor.withValues(alpha: 0.6),
                                  ),
                              maxLines: 1,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  String getSubtitle() {
    switch (widget.info.type) {
      case 'Movie':
        return widget.info.releaseDate?.substring(0, 4) ?? '';
      case 'TV':
        if (widget.info.localNumberOfSeasons > 1) {
          return '共${widget.info.localNumberOfSeasons}季·${widget.info.firstAirDate?.substring(0, 4)}-${widget.info.lastAirDate?.substring(0, 4)}';
        } else if (widget.info.localNumberOfSeasons == 1 &&
            widget.info.numberOfSeasons > 1) {
          return '第${widget.info.seasonNumber}季·${widget.info.releaseDate?.substring(0, 4)}';
        } else {
          return '共${widget.info.localNumberOfEpisodes}集·${widget.info.releaseDate?.substring(0, 4)}';
        }
      default:
        return '';
    }
  }
}
